package com.fubowen.lepton.ui.navigate

import android.graphics.Color
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.children
import androidx.fragment.app.activityViewModels
import androidx.navigation.NavController
import androidx.navigation.fragment.NavHostFragment
import com.fubowen.lepton.R
import com.fubowen.lepton.conf.Command
import com.fubowen.lepton.conf.SiteConfigViewModel
import com.fubowen.lepton.databinding.FragmentMoreMenuBinding
import com.fubowen.lepton.databinding.FragmentNavigateBinding
import com.fubowen.lepton.databinding.FragmentToolMenuBinding
import com.fubowen.lepton.helper.DBHelper
import com.fubowen.lepton.helper.ViewHelper.findViewsByTag
import com.fubowen.lepton.helper.ViewHelper.setVisible
import com.fubowen.lepton.helper.ViewHelper.toast
import com.google.android.material.bottomsheet.BottomSheetDialog
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class NavigateFragment : Fragment() {

    private lateinit var binding: FragmentNavigateBinding
    private val viewModel: SiteConfigViewModel by activityViewModels()
    private lateinit var host: NavHostFragment
    private lateinit var controller: NavController
    private val menuList = LinkedHashMap<Int, View>()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        binding = FragmentNavigateBinding.inflate(inflater, container, false)
        host = parentFragmentManager.findFragmentById(R.id.container_content) as NavHostFragment
        controller = host.navController
        initMenu()
        return binding.root
    }

    private fun initMenu() {
        binding.homeContainer.setOnClickListener { controller.navigate(R.id.homeFragment) }
        binding.bookContainer.setOnClickListener { controller.navigate(R.id.action_homeFragment_to_managerFragment) }
        binding.safeContainer.setOnClickListener {
            CoroutineScope(Dispatchers.IO).launch {
                val enableString = DBHelper.db.settingDao().get("isEnableSafe")
                val enable = enableString?.toBoolean() ?: false
                val tip = if (enable) "关闭无痕模式" else "开启无痕模式"
                binding.root.rootView.apply {
                    post {
                        toast(tip, 3000)
                    }
                }
                DBHelper.db.settingDao().set("isEnableSafe", (!enable).toString())
            }
        }
        binding.openContainer.setOnClickListener { viewModel.sendCommand(Command(it.id)) }
        controller.addOnDestinationChangedListener { _, desc, _ ->
            when (desc.id) {
                R.id.homeFragment -> {
                    binding.homeContainer.setVisible(false)
                    binding.toolContainer.setVisible(false)
                    binding.bookContainer.setVisible(true)
                    binding.safeContainer.setVisible(true)
                    binding.navMenu.setVisible(true)
                }

                R.id.managerFragment -> {
                    binding.navMenu.setVisible(false)
                }

                R.id.bookmarkGroupFragment -> {
                    binding.navMenu.setVisible(false)
                }

                R.id.readerFragment -> {
                    binding.navMenu.setVisible(false)
                }

                R.id.bookmarkGroupPreviewFragment -> {
                    binding.navMenu.setVisible(false)
                }

                R.id.bookmarkEditFragment -> {
                    binding.navMenu.setVisible(false)
                }

                else -> {
                    binding.homeContainer.setVisible(true)
                    binding.toolContainer.setVisible(true)
                    binding.bookContainer.setVisible(false)
                    binding.safeContainer.setVisible(false)
                    binding.navMenu.setVisible(true)
                }
            }
        }
        CoroutineScope(Dispatchers.Main).launch {
            viewModel.hasNavigation.collect { binding.navMenu.setVisible(it) }
        }
        binding.toolContainer.setOnClickListener { toolBottomPopupMenu.value.show() }
        binding.moreContainer.setOnClickListener { moreBottomPopupMenu.value.show() }
        viewModel.receiveCommand.observe(viewLifecycleOwner) {
            val color = if (it.isChecked) Color.GREEN else Color.WHITE
            val value = menuList[it.id]
            if (value is ViewGroup) {
                value.children.forEach { view ->
                    when (view) {
                        is TextView -> view.isSelected = it.isChecked
                        is ImageView -> view.isSelected = it.isChecked
                    }
                }
            }
        }
    }

    private val toolBottomPopupMenu = lazy {
        BottomSheetDialog(requireContext()).apply {
            val binding = FragmentToolMenuBinding.inflate(layoutInflater)
            val viewList = binding.root.findViewsByTag("button")
            if (viewList.isNotEmpty()) {
                for (view in viewList) {
                    menuList[view.id] = view
                    view.setOnClickListener {
                        val command = Command(
                            id = it.id
                        )
                        viewModel.sendCommand(command)
                        hide()
                    }
                }
            }
            setContentView(binding.root)
        }
    }

    private val moreBottomPopupMenu = lazy {
        BottomSheetDialog(requireContext()).apply {
            val binding = FragmentMoreMenuBinding.inflate(layoutInflater)
            val viewList = binding.root.findViewsByTag("button")
            if (viewList.isNotEmpty()) {
                for (view in viewList) {
                    menuList[view.id] = view
                    view.setOnClickListener {
                        val command = Command(
                            id = it.id
                        )
                        viewModel.sendCommand(command)
                    }
                }
            }
            setContentView(binding.root)
        }
    }
}